<template>
  <div class="order-test-container">
    <div class="header">
      <button class="back-btn" @click="goBack">←</button>
      <span class="title">RabbitMQ订单测试</span>
    </div>

    <!-- 测试状态 -->
    <div class="status-section">
      <div class="status-item" :class="{ 'success': connectionStatus, 'error': !connectionStatus }">
        <span class="status-dot"></span>
        <span>RabbitMQ连接状态: {{ connectionStatus ? '已连接' : '未连接' }}</span>
        <button class="test-btn" @click="testConnection">测试连接</button>
      </div>
    </div>

    <!-- 快速测试 -->
    <div class="quick-test-section">
      <h3>快速测试</h3>
      <div class="test-buttons">
        <button class="test-button" @click="createTestOrder">创建测试订单</button>
        <button class="test-button" @click="batchCreateOrders">批量创建订单</button>
        <button class="test-button" @click="clearTestData">清空测试数据</button>
      </div>
    </div>

    <!-- 订单创建表单 -->
    <div class="form-section">
      <h3>自定义订单测试</h3>
      <div class="form-group">
        <label>商品ID列表 (逗号分隔)</label>
        <input v-model="formData.goodsIds" placeholder="例如: 1,2,3" />
      </div>
      <div class="form-group">
        <label>商品数量列表 (逗号分隔)</label>
        <input v-model="formData.quantities" placeholder="例如: 2,1,3" />
      </div>
      <div class="form-group">
        <label>订单备注</label>
        <textarea v-model="formData.remark" placeholder="输入订单备注"></textarea>
      </div>
      <button class="submit-btn" @click="createCustomOrder" :disabled="creating">
        {{ creating ? '创建中...' : '创建订单' }}
      </button>
    </div>

    <!-- 订单状态查询 -->
    <div class="query-section">
      <h3>订单状态查询</h3>
      <div class="query-form">
        <input v-model="queryOrderNo" placeholder="输入订单号" />
        <button class="query-btn" @click="queryOrderStatus">查询状态</button>
      </div>
    </div>

    <!-- 测试结果 -->
    <div class="results-section" v-if="testResults.length > 0">
      <h3>测试结果</h3>
      <div class="results-list">
        <div 
          v-for="(result, index) in testResults" 
          :key="index"
          class="result-item"
          :class="{ 'success': result.success, 'error': !result.success }"
        >
          <div class="result-header">
            <span class="result-time">{{ formatTime(result.timestamp) }}</span>
            <span class="result-status">{{ result.success ? '成功' : '失败' }}</span>
          </div>
          <div class="result-content">
            <div class="result-action">{{ result.action }}</div>
            <div class="result-data" v-if="result.data">
              <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
            </div>
            <div class="result-error" v-if="result.error">
              <span class="error-text">{{ result.error }}</span>
            </div>
          </div>
        </div>
      </div>
      <button class="clear-results-btn" @click="clearResults">清空结果</button>
    </div>

    <!-- 实时日志 -->
    <div class="logs-section" v-if="logs.length > 0">
      <h3>实时日志</h3>
      <div class="logs-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.level">
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <span class="log-level">[{{ log.level.toUpperCase() }}]</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
      <button class="clear-logs-btn" @click="clearLogs">清空日志</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import orderService from '@/api/order-fixed'

const router = useRouter()

// 响应式数据
const connectionStatus = ref(false)
const formData = ref({
  goodsIds: '1,2',
  quantities: '2,1',
  remark: '测试订单'
})
const queryOrderNo = ref('')
const creating = ref(false)
const testResults = ref([])
const logs = ref([])

// 方法
const goBack = () => {
  router.go(-1)
}

const addLog = (level, message) => {
  logs.value.unshift({
    timestamp: new Date(),
    level,
    message
  })
  // 限制日志数量
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100)
  }
}

const addResult = (action, success, data = null, error = null) => {
  testResults.value.unshift({
    timestamp: new Date(),
    action,
    success,
    data,
    error
  })
  // 限制结果数量
  if (testResults.value.length > 50) {
    testResults.value = testResults.value.slice(0, 50)
  }
}

const testConnection = async () => {
  addLog('info', '开始测试RabbitMQ连接...')
  
  try {
    const result = await orderService.testConnection()
    
    if (result.code === 200) {
      connectionStatus.value = true
      addLog('success', 'RabbitMQ连接测试成功')
      addResult('连接测试', true, result.data)
    } else {
      connectionStatus.value = false
      addLog('error', 'RabbitMQ连接测试失败: ' + result.message)
      addResult('连接测试', false, null, result.message)
    }
  } catch (error) {
    connectionStatus.value = false
    addLog('error', 'RabbitMQ连接测试异常: ' + error.message)
    addResult('连接测试', false, null, error.message)
  }
}

const createTestOrder = async () => {
  addLog('info', '创建测试订单...')
  
  try {
    const orderData = {
      goods_ids: [1, 2],
      quantities: [1, 2],
      remark: `测试订单 - ${new Date().toLocaleString()}`
    }
    
    const result = await orderService.createOrder(orderData)
    
    if (result.code === 200) {
      addLog('success', `测试订单创建成功: ${result.data.order_no}`)
      addResult('创建测试订单', true, result.data)
      queryOrderNo.value = result.data.order_no
    } else {
      addLog('error', '测试订单创建失败: ' + result.message)
      addResult('创建测试订单', false, null, result.message)
    }
  } catch (error) {
    addLog('error', '测试订单创建异常: ' + error.message)
    addResult('创建测试订单', false, null, error.message)
  }
}

const batchCreateOrders = async () => {
  addLog('info', '开始批量创建订单...')
  
  const batchSize = 5
  const orders = []
  
  for (let i = 0; i < batchSize; i++) {
    orders.push({
      goods_ids: [Math.floor(Math.random() * 3) + 1],
      quantities: [Math.floor(Math.random() * 3) + 1],
      remark: `批量测试订单 ${i + 1} - ${new Date().toLocaleString()}`
    })
  }
  
  let successCount = 0
  let failCount = 0
  
  for (const orderData of orders) {
    try {
      const result = await orderService.createOrder(orderData)
      
      if (result.code === 200) {
        successCount++
        addLog('success', `批量订单创建成功: ${result.data.order_no}`)
      } else {
        failCount++
        addLog('error', '批量订单创建失败: ' + result.message)
      }
      
      // 添加延迟避免过快请求
      await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
      failCount++
      addLog('error', '批量订单创建异常: ' + error.message)
    }
  }
  
  addResult('批量创建订单', true, { 
    total: batchSize, 
    success: successCount, 
    failed: failCount 
  })
}

const createCustomOrder = async () => {
  if (creating.value) return
  
  creating.value = true
  addLog('info', '创建自定义订单...')
  
  try {
    // 解析输入数据
    const goodsIds = formData.value.goodsIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
    const quantities = formData.value.quantities.split(',').map(qty => parseInt(qty.trim())).filter(qty => !isNaN(qty))
    
    if (goodsIds.length === 0 || quantities.length === 0) {
      throw new Error('请输入有效的商品ID和数量')
    }
    
    if (goodsIds.length !== quantities.length) {
      throw new Error('商品ID和数量的数量必须一致')
    }
    
    const orderData = {
      goods_ids: goodsIds,
      quantities: quantities,
      remark: formData.value.remark || `自定义订单 - ${new Date().toLocaleString()}`
    }
    
    const result = await orderService.createOrder(orderData)
    
    if (result.code === 200) {
      addLog('success', `自定义订单创建成功: ${result.data.order_no}`)
      addResult('创建自定义订单', true, result.data)
      queryOrderNo.value = result.data.order_no
    } else {
      addLog('error', '自定义订单创建失败: ' + result.message)
      addResult('创建自定义订单', false, null, result.message)
    }
  } catch (error) {
    addLog('error', '自定义订单创建异常: ' + error.message)
    addResult('创建自定义订单', false, null, error.message)
  } finally {
    creating.value = false
  }
}

const queryOrderStatus = async () => {
  if (!queryOrderNo.value.trim()) {
    addLog('warn', '请输入订单号')
    return
  }
  
  addLog('info', `查询订单状态: ${queryOrderNo.value}`)
  
  try {
    const result = await orderService.getOrderStatus(queryOrderNo.value.trim())
    
    if (result.code === 200) {
      addLog('success', `订单状态查询成功: ${result.data.status}`)
      addResult('查询订单状态', true, result.data)
    } else {
      addLog('error', '订单状态查询失败: ' + result.message)
      addResult('查询订单状态', false, null, result.message)
    }
  } catch (error) {
    addLog('error', '订单状态查询异常: ' + error.message)
    addResult('查询订单状态', false, null, error.message)
  }
}

const clearTestData = () => {
  if (confirm('确定要清空所有测试数据吗？')) {
    testResults.value = []
    logs.value = []
    queryOrderNo.value = ''
    addLog('info', '测试数据已清空')
  }
}

const clearResults = () => {
  testResults.value = []
  addLog('info', '测试结果已清空')
}

const clearLogs = () => {
  logs.value = []
}

const formatTime = (date) => {
  return new Date(date).toLocaleTimeString()
}

// 生命周期
onMounted(async () => {
  addLog('info', '订单测试页面已加载')
  await testConnection()
})
</script>

<style scoped>
.order-test-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20px;
}

.header {
  position: sticky;
  top: 0;
  background: #fff;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid #eee;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
}

.title {
  font-weight: 600;
  font-size: 16px;
}

.status-section,
.quick-test-section,
.form-section,
.query-section,
.results-section,
.logs-section {
  background: #fff;
  margin: 12px 16px;
  padding: 16px;
  border-radius: 8px;
}

.status-section h3,
.quick-test-section h3,
.form-section h3,
.query-section h3,
.results-section h3,
.logs-section h3 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
}

.status-item.success {
  background: #d4edda;
  color: #155724;
}

.status-item.error {
  background: #f8d7da;
  color: #721c24;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.success .status-dot {
  background: #28a745;
}

.error .status-dot {
  background: #dc3545;
}

.test-btn {
  margin-left: auto;
  background: #007bff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.test-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.test-button {
  background: #6c757d;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.test-button:hover {
  background: #5a6268;
}

.form-group {
  margin-bottom: 12px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 600;
  color: #333;
  font-size: 12px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.form-group textarea {
  min-height: 60px;
  resize: vertical;
}

.submit-btn {
  width: 100%;
  background: #28a745;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.query-form {
  display: flex;
  gap: 8px;
}

.query-form input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.query-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.results-list {
  max-height: 300px;
  overflow-y: auto;
}

.result-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 8px;
  overflow: hidden;
}

.result-item.success {
  border-color: #28a745;
}

.result-item.error {
  border-color: #dc3545;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.result-time {
  font-size: 11px;
  color: #666;
}

.result-status {
  font-size: 11px;
  font-weight: 600;
}

.success .result-status {
  color: #28a745;
}

.error .result-status {
  color: #dc3545;
}

.result-content {
  padding: 8px 12px;
}

.result-action {
  font-weight: 600;
  margin-bottom: 4px;
  font-size: 12px;
}

.result-data pre {
  background: #f8f9fa;
  padding: 8px;
  border-radius: 4px;
  font-size: 10px;
  overflow-x: auto;
  margin: 4px 0;
}

.result-error {
  color: #dc3545;
  font-size: 11px;
}

.clear-results-btn,
.clear-logs-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 11px;
  cursor: pointer;
  margin-top: 8px;
}

.logs-container {
  max-height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 8px;
}

.log-item {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 11px;
  font-family: monospace;
}

.log-time {
  color: #666;
  white-space: nowrap;
}

.log-level {
  font-weight: 600;
  white-space: nowrap;
}

.log-item.info .log-level {
  color: #007bff;
}

.log-item.success .log-level {
  color: #28a745;
}

.log-item.warn .log-level {
  color: #ffc107;
}

.log-item.error .log-level {
  color: #dc3545;
}

.log-message {
  flex: 1;
  word-break: break-word;
}
</style>
